// pages/order/order.js
import { Order } from '../order/order-model.js';
import { Cart } from '../cart/cart-model.js';
import { Address } from '../../utils/address.js';
var order = new Order();
var cart = new Cart();
var address = new Address();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromCartFlag: true,
    addressInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var flag = options.from == 'cart',
      that = this;
    this.data.fromCartFlag = flag;
    this.data.account = options.account;

    // 订单来自购物车
    if (flag) {
      this.setData({
        productsArr: cart.getCartDataFromLocal(true),
        account: options.account,
        orderStatus: 0
      });

      // 显示收货地址
      address.getAddress((res) => {
        that._bindAddressInfo(res);
      });
    } else {
      // 旧订单
      this.data.id = options.id;
    }
  },

  onShow: function () {
    // 下单后，支付成功或者失败后，点左上角返回时能够更新订单状态，所以放在onshow中
    if (this.data.id) {
      var that = this;
      var id = this.data.id;
      order.getOrderInfoById(id,(data)=>{
        that.setData({
          orderStatus:data.status,
          productsArr:data.snap_items,
          account:data.total_price,
          basicInfo:{
            orderTime:data.create_time,
            orderNo:data.order_no
          }
        });
      });
      // 快照地址
      var addressInfo = data.snap_address;
      addressInfo.totalDetail = address.setAddressInfo(addressInfo);
      that._bindAddressInfo(addressInfo);
    }
  },

  /**
   * 添加或修改地址信息
   */
  editAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        var addressInfo = {
          name: res.userName,
          mobile: res.telNumber,
          totalDetail: address.setAddressInfo(res)
        };
        that._bindAddressInfo(addressInfo);
        address.submitAddress(res, (flag) => {
          if (!flag) {
            that.showTips('操作提示', '地址信息更新失败！');
          }
        });
      }
    })
  },

  /**
   * 绑定地址信息
   */
  _bindAddressInfo: function (addressInfo) {
    this.setData({
      addressInfo: addressInfo
    });
  },

  /**
   * 下单和付款
   */
  pay:function(){
    if(!this.data.addressInfo){
      this.showTips('下单提示','请填写您的收货地址');
      return;
    }
    if(this.data.orderStatus == 0){
      // 从购物车过来的订单，首次付款
      this._firstTimePay();
    }else{
      this._oneMoresTimePay();
    }
  },

  /**
   * 第一次支付
   */
  _firstTimePay:function(){
    var orderInfo = [],
    productInfo = this.data.productsArr,
    order = new Order();
    for(let i = 0;i < productInfo.length;i++){
      orderInfo.push({
        product_id:productInfo[i].id,
        count:productInfo[i].counts
      });
    }

    var that = this;
    // 支付分两步，第一步是生成订单号，第二步是根据订单号进行支付
    order.doOrder(orderInfo,(data)=>{
      // 订单生成成功
      if(data.pass){
        // 更新订单状态
        var id = data.order_id;
        that.data.id = id;
        that.data.fromCartFlag = false;

        // 开始支付
        that._execPay(id);
      }else{
        // 下单失败
        that._orderFail(data);
      }
    });
  },

  /**
   * 下单失败
   */
  _orderFail:function(data){
    var nameArr = [],
    name = '',
    str = '',
    pArr = data.pStatusArray;
    for(let i=0;i < pArr.length;i++){
      if(!pArr[i].haveStock){
        name = pArr[i].name;
        if(name.length > 15){
          name = name.substr(0,12) + '...';
        }
        nameArr.push(name);
        if(nameArr.length >= 2){
          break;
        }
      }
    }
    str += nameArr.join('、');
    if(nameArr.length > 2){
      str += ' 等';
    }
    str += ' 缺货';
    this.showTips('下单失败',str);
  },

  /**
   * 开始支付
   * @params int id 订单号
   */
  _execPay:function(id){
    if(!order.onPay){
      this.showTips('支付提示','本产品仅用于演示，支付系统已屏蔽',true);
      this.deleteProducts(); // 将已经下单的商品从购物车删除
      return;
    }
    var that = this;
    order.execPay(id,(statusCode)=>{
      if(statusCode != 0){
        that.deleteProducts();
        var flag = statusCode == 2;
        wx.navigateTo({
          url: '../pay-result/pay-result?id=' + id + '&flag=' + flag + '&from=order',
        })
      }
    });
  },

  /**
   * 将已经下单的商品从购物车删除
   */
  deleteProducts:function(){
    var ids = [],
    arr = this.data.productsArr;
    for(let i=0;i < arr.length;i++){
      ids.push(arr[i].id);
    }
    cart.delete(ids);
  },

  /**
   * 提示窗口
   * @param string title 标题
   * @param string content 内容
   * @param boolean flag 是否跳转到‘我的’页面
   */
  showTips: function (title, content, flag) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function (res) {
        if (flag) {
          wx.switchTab({
            url: '/pages/my/my',
          })
        }
      }
    })
  }
})